package com.hup.sidebar.framework;

import android.os.Handler;
import android.os.HandlerThread;

import androidx.core.util.Consumer;

/**
 * @author hugan
 * @date 2022/4/3
 */
public class SubThreadHandler extends Handler {

    public SubThreadHandler(String threadName) {
        super(buildThread(threadName).getLooper());
    }

    private static HandlerThread buildThread(String threadName) {
        HandlerThread handlerThread = new HandlerThread(threadName);
        handlerThread.start();
        return handlerThread;
    }

    /**
     * 设置线程异常处理器
     *
     * @apiNote 注意, 一旦 consumer被调用,意味着Handler已经不能再处理消息了,Looper线程已损坏
     */
    public void setExceptionHandler(Consumer<Throwable> consumer) {
        post(() -> Thread.setDefaultUncaughtExceptionHandler((t, e) -> consumer.accept(e)));
    }

}
